package com.szholly.utils.session;

import java.util.HashMap;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.szholly.utils.util.StringUtils;

/**
 * 获取当前Session对象
 */
public class CurrentSessionHelper {
	
	/**
	 * 当前在线用户的缓存
	 */
	private static HashMap<String, HttpSession> NameSessionCache = new HashMap<String, HttpSession>();
	
	/**
	 * 获取当在线前用户信息
	 * @return
	 */
	public static String[] getOnlineUsers(){
		Set<String> keys = NameSessionCache.keySet();
		String[] names = new String[keys.size()];
		keys.toArray(names);
		return names;
	}
	
	/**
	 * 获取当前在线用户数量
	 * @return
	 */
	public static int getOnlineUserCount(){
		return NameSessionCache.size();
	}
	
	/**
	 * 处理一个用户只能登录一次
	 * @param userName
	 */
	public static void optionSession(String userName, HttpSession session){
		if(session==null){
			return;
		}
		if(NameSessionCache.containsKey(userName)){
			HttpSession oldSession = NameSessionCache.get(userName);
			if(oldSession!=null && !oldSession.getId().equals(session.getId())){
				try{
					oldSession.invalidate();
				}catch(Exception e){}
				NameSessionCache.remove(userName);
				NameSessionCache.put(userName, session);
			}
		}else{
			NameSessionCache.put(userName, session);
		}
	}
	
	/**
	 * 移除用户
	 * @param userName
	 */
	public static void removeUser(String userName){
		if(StringUtils.IsNullOrSpace(userName)){
			return;
		}
		if(NameSessionCache.containsKey(userName)){
			NameSessionCache.remove(userName);
		}
	}
	
	/**
	 * 获取当前的Session
	 * @return
	 */
	public static HttpSession getCurrentSession(){
		RequestAttributes obj = null;
		try {
			obj = RequestContextHolder.currentRequestAttributes();
		} catch (Exception e) {
		}
		if(obj==null){
			return null;
		}
		
		ServletRequestAttributes attr = null;
		if(obj instanceof ServletRequestAttributes){
			attr = (ServletRequestAttributes) obj;
		}
		if(attr==null){
			return null;
		}
		
        HttpSession session = attr.getRequest().getSession(true);
        return session;
	}
	
	public static HttpServletRequest getCurrentHttpServletRequest(){
		RequestAttributes obj = null;
		try {
			obj = RequestContextHolder.currentRequestAttributes();
		} catch (Exception e) {
		}
		if(obj==null){
			return null;
		}
		
		ServletRequestAttributes attr = null;
		if(obj instanceof ServletRequestAttributes){
			attr = (ServletRequestAttributes) obj;
		}
		if(attr==null){
			return null;
		}
		
		return attr.getRequest();
	}
}
